<?php
/**
 * Created by PhpStorm.
 * User: refar
 * Date: 21-07-21
 * Time: 下午1:17
 */

namespace app\v2\controller;
use ext\MailTemplateV2;
use ext\MailTemplateV3;
use think\Db;
use think\Exception;
use think\Log;

class Flow2 extends Common {
//    public function borrowApply() {
//
//        try {
//
//            // 前端需要把数组变成字符串
//            $fixed_nos = json_decode($this->request->param('fixed_nos'));// 转为数组
//            $predictDate = $this->request->param('predictDate'); // 预计归还时间
//            $actualUser = $this->request->param('actualUser'); // 实际使用者
//            $purpose = $this->request->param('purpose'); // 使用目的
//
//            // 需要插入的数据
//            $inputData = array();
//
//            $node = Db::table('sms_approve_node')->where('node_number', 1)
//                ->where('flow_name', '借出')->find();
//
//            for ($i = 0; $i < count($fixed_nos); $i++) {
//
//                $query = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
//                    ->where('model_status', $node['target_status'])->where('user_id', null)->find();
//                if (!empty($query)) {
//                    // 更新状态
//                    $res = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
//                        ->where('model_status', $node['target_status'])->where('user_id', null)
//                        ->update([
//                            'user_name'    => $this->loginUser['name'],
//                            'user_id'      => $this->loginUser['T'],
//                            'model_status' => $node['next_status'],
//                            'predict_date'  => $predictDate,
//                            'actual_user_name'=> $actualUser,
//                            'purpose'=>$purpose
//                        ]);
//
//                    // 更新成功
//                    if (1 == $res) {
//                        $inputData[$query['borrow_classify']][] = array('id'=>$query['fixed_no'] ,
//                            'name'=>$query['MODEL_NAME'], 'desc'=>$query['remark']);
//
//                            $this->insertLogRecord($query, $node, null, 'agree');
//                    } else {
//                        Log::record('[Flow][borrowApply] update fail ' . $fixed_nos[$i]);
//                    }
//
//                }
//            }
//
//            // 存入邮件队列表中
//            if (!empty($inputData)) {
//                foreach ($inputData as $classify => $value) {
//
//                    $node = Db::table('sms_approve_node')->where('agree_mailto_depart', $classify)
//                        ->where('flow_name', '借出')->find();
//                    // 插入数据
//                    $data = ['id'=>null,
//                        'type'=>getMyType(APPLY),
//                        'main_body'=>MailTemplateV3::getBorrow(),
//                        'subject'=>config('mail_header_subject'). MailTemplateV3::$subjectBorrow. $this->loginUser['depart']. ' '
//                        .$this->loginUser['name'],
//                        'from'=>$this->loginUser['email'],
//                        'to'=>json_encode($this->getAddressByNode($node, 'BANDD')),
//                        'table_data' => json_encode($value)];
//                    Db::table('ems_mail_queue')->insert($data);
//                }
//                return apiResponse(SUCCESS, '[Flow][borrowApply] success');
//            }
//
//        } catch (Exception $e) {
//            Log::record('[Flow][borrowApply] error ' . $e->getMessage());
//            return apiResponse(ERROR, 'server error');
//
//        }
//        return apiResponse(ERROR, 'server error');
//    }

    /**
     * showdoc
     * @catalog 接口文档-V2/流程相关/申请
     * @title 样品销售申请
     * @description 样品销售申请
     * @method get
     * @param fixed_nos 必选 string fixed_nos=[]
     * @param saleTarget 必选 string
     * @return {"status":0,"msg":"[Flow][saleApply] success","data":[]}
     * @url http://domain/ems-api/v2/Flow2/saleApply
     * @remark 1.销售管理员(销售申请)->销售部长->总经理->财务课长->财务部长; 2.返回状态1代表失败
     */
    public function saleApply() {
        try {

            // 前端需要把数组变成字符串
            $fixed_nos = json_decode($this->request->param('fixed_nos'));// 转为数组
            $saleTarget = $this->request->param('saleTarget');

            // 需要插入的数据
            $inputData = array();

            $node = Db::table('sms_approve_node')->where('roleId', $this->loginUser['roleId'])
                ->where('depart', $this->loginUser['depart'])->where('node_number', 1)
                ->where('flow_name', '销售')->find();

            for ($i = 0; $i < count($fixed_nos); $i++) {

                $query = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                    ->where('model_status', $node['target_status'])->where('user_id', null)->find();
                if (!empty($query)) {
                    // 更新状态
                    $res = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                        ->where('model_status', $node['target_status'])->where('user_id', null)
                        ->update([
                            'model_status'    => $node['next_status'],
                            'sale_apply_operator'      => $this->loginUser['name'],
                            'sale_apply_date' => Db::raw('now()'),
                            'sale_target'=>$saleTarget
                        ]);

                    // 更新成功
                    if (1 == $res) {
                        $inputData[] = array('id' => $query['fixed_no'], 'name' => $query['MODEL_NAME'],
                            'desc' => $query['remark']);

                        $this->insertSaleLogRecord($query, $node, null, 'agree');
                    } else {
                        Log::record('[Flow][saleApply] update fail ' . $fixed_nos[$i]);
                    }

                }
            }
            $this->processSaleMail($inputData, $node, null);

        } catch (Exception $e) {
            Log::record('[Flow][saleApply] error' . $e->getMessage());
            return apiResponse(ERROR, 'server error');

        }

        return apiResponse(SUCCESS, '[Flow][saleApply] success');

    }
    /**
     * showdoc
     * @catalog 接口文档-V2/流程相关/审批
     * @title 样品销售审批
     * @description 样品销售审批
     * @method get
     * @param fixed_nos 必选 string fixed_nos=[]
     * @param judge 必选 string agree/disagree
     * @param sale_remark 不管同意拒绝都要提交 string
     * @return {"status":0,"msg":"[Flow][replySaleApply] success","data":[]}
     * @url http://domain/ems-api/v2/Flow2/replySaleApply
     * @remark 1.销售管理员(销售申请)->销售部长->总经理->财务课长->财务部长; 2.返回状态1代表失败
     */
    public function replySaleApply() {
        $judge = $this->request->param('judge');
        $fixed_nos = json_decode($this->request->param('fixed_nos'));
        $saleRemark = $this->request->param('sale_remark');
        $inputData = array();

        // 根据roleId & depart判断是哪个角色以及哪个节点
        try {

            $node = Db::table('sms_approve_node')->where('roleId', $this->loginUser['roleId'])
                ->where('depart', $this->loginUser['depart'])->where('flow_name', '销售')->find();

            if (!empty($node)) {
                if ('agree' == $judge) {
                    for ($i = 0; $i < count($fixed_nos); $i++) {
                        $query = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                            ->where('model_status', $node['target_status'])->find();

                        if (!empty($query)) {
                            $res = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                                ->where('model_status', $node['target_status'])
                                ->update([
                                    'model_status' => $node['next_status'],
                                    'approver_id' => $this->loginUser['T'],
                                    'approve_date' => Db::raw('now()'),
                                    'approver_name' => $this->loginUser['name']
                                ]);
                            if (1 == $res) {
                                $inputData[] = array('id' => $query['fixed_no'], 'name' => $query['MODEL_NAME'],
                                    'desc' => $query['remark']);

                                $this->insertSaleLogRecord($query, $node, $saleRemark, $judge);
                            } else {
                                Log::record('[Flow][replySaleApply] update fail ' . $fixed_nos[$i]);
                            }
                        } else {
                            Log::record('[Flow][replySaleApply] no data ' . $fixed_nos[$i]);
                        }
                    }
                } else {
                    // 更新状态到在库
                    for ($i = 0; $i < count($fixed_nos); $i++) {
                        $query = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                            ->where('model_status', $node['target_status'])->find();

                        if (!empty($query)) {
                            $res = Db::table('sms_main_engine')->where('fixed_no', $fixed_nos[$i])
                                ->where('model_status', $node['target_status'])
                                ->update([
                                    'model_status' => $node['reject_status'],
                                    'sale_apply_operator' => null,
                                    'sale_apply_date' => null,
                                    'sale_target' => null
                                ]);

                            if (1 == $res) {
                                $inputData[] = array('id' => $query['fixed_no'], 'name' => $query['MODEL_NAME'],
                                    'desc' => $query['remark']);

                                $this->insertSaleLogRecord($query, $node, $saleRemark, $judge);
                            } else {
                                Log::record('[Flow][replySaleApply] update fail ' . $fixed_nos[$i]);
                            }
                        } else {
                            Log::record('[Flow][replySaleApply] no data ' . $fixed_nos[$i]);
                        }
                    }

                }
            } else {
                Log::record('[Flow][replySaleApply] no $node');
            }

        } catch (Exception $e) {
            Log::record('[Flow][replySaleApply] error ' . $e->getMessage());
            return apiResponse(ERROR, 'server error');

        }

        $this->processSaleMail($inputData, $node, $judge);

        return apiResponse(SUCCESS, '[Flow][replySaleApply] success');
    }

    private function getAddressByNode($node, $judge) {
        $address = array();
        $res = null;
        try {
            if ('BANDD' == $judge) {
                $res = Db::table('users')->where('role_id', $node['agree_mailto_roleId'])
                    ->field('email')->select();
            }elseif ('agree' == $judge || empty($judge)) {
                $res = Db::table('users')->where('role_id', $node['agree_mailto_roleId'])
                    ->where('department', $node['agree_mailto_depart'])->field('email')->select();
            } else {
                $res = Db::table('users')->where('role_id', $node['reject_mailto'])
                    ->field('email')->select();
            }


            foreach ($res as $k => $v) {
                $address[] = $v['email'];
            }
            return $address;
        } catch (Exception $e) {
            Log::record('[Flow][getAddressByNode] error' . $e->getMessage());
            return apiResponse(ERROR, 'server error');
        }
    }

//    private function insertLogRecord($query, $node, $reason, $judge) {
//        try {
//            Db::table('sms_log_record')->insert([
//                'id'=>null,
//                'fixed_no'=>$query['fixed_no'],
//                'desc'=>$node['log_flow'],
//                'role'=>$this->loginUser['desc'],
//                'operator'=>$this->loginUser['name'],
//                'type'=>$node['log_type'],
//                'result'=> ($judge == 'agree') ? $node['log_result_agree'] : $node['log_result_disagree'],
//                'reason'=>$reason,
//                'time'=>Db::raw('now()')
//            ]);
//
//        } catch (Exception $e) {
//            Log::record('[Flow][insertSaleLogRecord] error ' . $e->getMessage());
//            return apiResponse(ERROR, 'server error');
//        }
//
//    }

    private function insertSaleLogRecord($query, $node, $saleRemark, $judge) {
        try {
            Db::table('sms_log_record')->insert([
                'id'=>null,
                'fixed_no'=>$query['fixed_no'],
                'desc'=>$node['log_flow'],
                'role'=>$node['remark'],
                'operator'=>$this->loginUser['name'],
                'type'=>$node['log_type'],
                'result'=> ($judge == 'agree') ? $node['log_result_agree'] : $node['log_result_disagree'],
                'remark_sale'  => $saleRemark,
                'time'=>Db::raw('now()')
            ]);

        } catch (Exception $e) {
            Log::record('[Flow][insertSaleLogRecord] error ' . $e->getMessage());
            return apiResponse(ERROR, 'server error');
        }

    }

    private function processSaleMail($inputData, $node, $judge) {

        if (!empty($inputData)) {
            $res = Db::table('ems_mail_queue')->insert([
                'id'=>null,
                'type'=>getMyType(FLOW),
                'main_body'=>MailTemplateV3::getSale(),
                'subject'=>config('mail_header_subject'). MailTemplateV3::$subjectSale. $this->loginUser['name'],
                'from'=>$this->loginUser['email'],
                'to'=>json_encode($this->getAddressByNode($node, $judge)),
                'table_data' => json_encode($inputData)]);

            if (1 == $res) {
                return apiResponse(SUCCESS, '[Flow][processSaleMail] success');
            }
            return apiResponse(ERROR, 'server error');
        }
    }
}